<template>
  <div class="app-container">
    <!-- 搜索表单 -->
    <el-card class="search-card">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px">
        <el-form-item label="房间名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入房间名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="房间类型" prop="type">
          <el-select v-model="queryParams.type" placeholder="房间类型" clearable style="width: 200px">
            <el-option label="公开房间" value="PUBLIC" />
            <el-option label="私有房间" value="PRIVATE" />
            <el-option label="群聊" value="GROUP" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="房间状态" clearable style="width: 200px">
            <el-option label="活跃" value="ACTIVE" />
            <el-option label="已关闭" value="CLOSED" />
            <el-option label="已禁用" value="DISABLED" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作工具栏 -->
    <el-card class="toolbar-card">
      <el-row :gutter="16" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="Plus"
            class="toolbar-button is-primary"
            @click="handleAdd"
          >新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="Edit"
            :disabled="single"
            class="toolbar-button is-success"
            @click="handleUpdate"
          >修改</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="Delete"
            :disabled="multiple"
            class="toolbar-button is-danger"
            @click="handleDelete"
          >删除</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 聊天室表格 -->
    <el-card>
      <el-table
        v-loading="loading"
        :data="roomList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="房间名称" align="center" prop="name" :show-overflow-tooltip="true" />
        <el-table-column label="房间类型" align="center" width="100">
          <template #default="scope">
            <el-tag :type="getTypeTag(scope.row.type)">
              {{ getTypeText(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建者" align="center" prop="creatorName" width="120" />
        <el-table-column label="成员数量" align="center" prop="memberCount" width="100" />
        <el-table-column label="消息数量" align="center" prop="messageCount" width="100" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              active-value="ACTIVE"
              inactive-value="DISABLED"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="250" class-name="small-padding fixed-width">
          <template #default="scope">
            <div class="table-operation-wrapper">
              <el-button
                type="primary"
                icon="Edit"
                @click="handleUpdate(scope.row)"
                class="table-operation-button is-primary"
                size="small"
              >修改</el-button>
              <el-button
                type="danger"
                icon="Delete"
                @click="handleDelete(scope.row)"
                class="table-operation-button is-danger"
                size="small"
              >删除</el-button>
              <el-dropdown @command="(command) => handleCommand(command, scope.row)">
                <el-button
                  type="warning"
                  class="table-operation-button is-warning"
                  size="small"
                >
                  更多<el-icon class="el-icon--right"><arrow-down /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item command="handleMembers" icon="User">成员管理</el-dropdown-item>
                    <el-dropdown-item command="handleMessages" icon="ChatDotRound">消息记录</el-dropdown-item>
                    <el-dropdown-item command="handleStatistics" icon="DataAnalysis">数据统计</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <Pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加或修改聊天室对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="roomFormRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="房间名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入房间名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="房间类型" prop="type">
              <el-select v-model="form.type" placeholder="请选择房间类型" style="width: 100%">
                <el-option label="公开房间" value="PUBLIC" />
                <el-option label="私有房间" value="PRIVATE" />
                <el-option label="群聊" value="GROUP" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大成员数" prop="maxMembers">
              <el-input-number v-model="form.maxMembers" :min="2" :max="1000" controls-position="right" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="房间描述" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入房间描述" :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否需要密码">
              <el-radio-group v-model="form.needPassword">
                <el-radio :value="true">是</el-radio>
                <el-radio :value="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.needPassword">
            <el-form-item label="房间密码" prop="password">
              <el-input v-model="form.password" placeholder="请输入房间密码" show-password />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="允许匿名">
              <el-radio-group v-model="form.allowAnonymous">
                <el-radio :value="true">是</el-radio>
                <el-radio :value="false">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="消息审核">
              <el-radio-group v-model="form.messageModeration">
                <el-radio :value="true">开启</el-radio>
                <el-radio :value="false">关闭</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getChatRooms, createChatRoom, updateChatRoom, deleteChatRoom, updateChatRoomStatus } from '@/api/chat'
import Pagination from '@/components/Pagination/index.vue'

// 响应式数据
const loading = ref(true)
const ids = ref([])
const single = ref(true)
const multiple = ref(true)
const total = ref(0)
const roomList = ref([])
const title = ref('')
const open = ref(false)
const queryFormRef = ref()
const roomFormRef = ref()

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  type: undefined,
  status: undefined
})

// 表单数据
const form = reactive({
  id: undefined,
  name: undefined,
  type: 'PUBLIC',
  description: undefined,
  maxMembers: 100,
  needPassword: false,
  password: undefined,
  allowAnonymous: false,
  messageModeration: false
})

// 表单校验规则
const rules = reactive({
  name: [{ required: true, message: '房间名称不能为空', trigger: 'blur' }],
  type: [{ required: true, message: '房间类型不能为空', trigger: 'change' }],
  maxMembers: [{ required: true, message: '最大成员数不能为空', trigger: 'blur' }]
})

// 获取聊天室列表
const getList = async () => {
  loading.value = true
  try {
    const response = await getChatRooms(queryParams)
    if (response.code === 200) {
      roomList.value = response.data.records || []
      total.value = response.data.total || 0
    } else {
      ElMessage.error(response.message || '获取聊天室列表失败')
    }
  } catch (error) {
    console.error('获取聊天室列表失败:', error)
    ElMessage.error('获取聊天室列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索按钮操作
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮操作
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加聊天室'
}

// 修改按钮操作
const handleUpdate = (row) => {
  reset()
  const roomId = row.id || ids.value[0]
  Object.assign(form, row)
  open.value = true
  title.value = '修改聊天室'
}

// 删除按钮操作
const handleDelete = (row) => {
  const roomIds = row.id ? [row.id] : ids.value
  ElMessageBox.confirm('是否确认删除聊天室编号为"' + roomIds + '"的数据项？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteChatRoom(roomIds[0])
      getList()
      ElMessage.success('删除成功')
    } catch (error) {
      console.error('删除聊天室失败:', error)
      ElMessage.error('删除聊天室失败')
    }
  }).catch(() => {})
}

// 聊天室状态修改
const handleStatusChange = async (row) => {
  const text = row.status === 'ACTIVE' ? '启用' : '禁用'
  try {
    await ElMessageBox.confirm('确认要"' + text + '""' + row.name + '"聊天室吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await updateChatRoomStatus(row.id, row.status)
    if (response.code === 200) {
      ElMessage.success(text + '成功')
      getList() // 刷新列表
    } else {
      ElMessage.error(response.message || text + '失败')
      row.status = row.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE'
    }
  } catch (error) {
    if (error !== 'cancel') {
      row.status = row.status === 'ACTIVE' ? 'DISABLED' : 'ACTIVE'
      ElMessage.error(text + '失败')
    }
  }
}

// 更多操作触发
const handleCommand = (command, row) => {
  switch (command) {
    case 'handleMembers':
      handleMembers(row)
      break
    case 'handleMessages':
      handleMessages(row)
      break
    case 'handleStatistics':
      handleStatistics(row)
      break
    default:
      break
  }
}

// 成员管理
const handleMembers = (row) => {
  ElMessage.info('跳转到成员管理页面')
}

// 消息记录
const handleMessages = (row) => {
  ElMessage.info('跳转到消息记录页面')
}

// 数据统计
const handleStatistics = (row) => {
  ElMessage.info('显示数据统计')
}

// 工具函数
const getTypeTag = (type) => {
  const typeMap = {
    'PUBLIC': 'success',
    'PRIVATE': 'warning',
    'GROUP': 'info'
  }
  return typeMap[type] || 'info'
}

const getTypeText = (type) => {
  const textMap = {
    'PUBLIC': '公开房间',
    'PRIVATE': '私有房间',
    'GROUP': '群聊'
  }
  return textMap[type] || type
}

// 表单重置
const reset = () => {
  Object.assign(form, {
    id: undefined,
    name: undefined,
    type: 'PUBLIC',
    description: undefined,
    maxMembers: 100,
    needPassword: false,
    password: undefined,
    allowAnonymous: false,
    messageModeration: false
  })
  roomFormRef.value?.resetFields()
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 提交表单
const submitForm = () => {
  roomFormRef.value?.validate(async (valid) => {
    if (valid) {
      try {
        if (form.id) {
          await updateChatRoom(form.id, form)
          ElMessage.success('修改成功')
        } else {
          await createChatRoom(form)
          ElMessage.success('新增成功')
        }
        open.value = false
        getList()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('操作失败')
      }
    }
  })
}

// 时间格式化
const parseTime = (time) => {
  if (!time) return ''
  const date = new Date(time)
  return date.toLocaleString()
}

// 页面加载时获取数据
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.search-card {
  margin-bottom: 16px;
}

.toolbar-card {
  margin-bottom: 16px;
}

.mb8 {
  margin-bottom: 8px;
}
</style>
